package core.storage;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Class modeling the Binary Serialization
 * 
 * @author Nolan Potier
 * @version 1.0.0
 * 
 */
public class BinarySerializer {

    /**
     * Load an object with a file name
     * @param fileName
     * @return object
     */
    public static Object load(String fileName) {
        Object res = null;
        try {
            FileInputStream fis = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(fis);
            try {
                res = ois.readObject();
            } finally {
                try {
                    ois.close();
                } finally {
                    fis.close();
                }
            }
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        }
        return res;
    }

    /**
     * Store an object in binary
     * @param object
     * @param fileName
     * @return boolean
     */
    public static boolean store(Object object, String fileName) {
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            try {
                oos.writeObject(object);
                oos.flush();
            } finally {
                try {
                    oos.close();
                } finally {
                    fos.close();
                }
            }
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            return false;
        }
        return true;
    }

}
